package com.tzbank.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author youkun
 * 错误异常
 */
@Component
public class ErrorFilter  extends ZuulFilter{

    @Override
    public String filterType() {
        return "error";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        //设置返回的字符编码
        ctx.getResponse().setCharacterEncoding("UTF-8");
        Throwable throwable = ctx.getThrowable();
        if(throwable!=null){
              Map<String,Object> map = new HashMap<String,Object>();
              map.put("msg",throwable.getCause().getMessage());
              map.put("code","-1");
              ctx.setResponseBody(JSON.toJSONString(map));
        }
        return null;
    }
}
